﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using SaleManagement.Web.App_Code;
using SaleManagement.Domains;
using SaleManagement.Services;
using System.Transactions;

namespace SaleManagement.Web.Pages
{
  public partial class AccessoryInfo : BasePage
  {
    #region Variables and properties
    private string _InnerError = string.Empty;

    private DataTable AccImportDetailTable
    {
      get
      {
        if (Session["AccImportDetailTable"] == null)
        {
          DataTable table = new DataTable();
          Session["AccImportDetailTable"] = table;
        }
        return Session["AccImportDetailTable"] as DataTable;
      }

      set
      {
        Session["AccImportDetailTable"] = value;
      }
    }

    private int DetailId
    {
      get
      {
        if (Session["AccImportDetailId"] == null)
        {
          Session["AccImportDetailId"] = 0;
        }

        return Convert.ToInt32(Session["AccImportDetailId"]);
      }

      set
      {
        Session["AccImportDetailId"] = value;
      }
    }
    #endregion

    #region Events
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsPostBack && !IsCallback)
      {
        if (!string.IsNullOrEmpty(Request.QueryString["id"]))
        {
          hfAccessoryId.Value = Request.QueryString["id"];
        }

        LoadCommonInfo();
        LoadAccessoryDetailList();
      }
    }

    protected void gvAccessoryDetail_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
    {
      string[] para = e.Parameters.Split('|');
      switch (para[0])
      {
        case "DeleteDetail":
          _InnerError = DeleteAccessoryDetail(Convert.ToInt32(para[1]));
          break;
        case "SaveDetail":
          _InnerError = SaveAccessoryDetail();
          break;
        case "Save":
          _InnerError = Save();
          break;
        default:
          break;
      }

      LoadAccessoryDetailList();
    }

    protected void gvAccessoryDetail_CustomJSProperties(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewClientJSPropertiesEventArgs e)
    {
      e.Properties["cpInnerError"] = _InnerError;
    }

    protected void gvAccessoryDetail_PageIndexChanged(object sender, EventArgs e)
    {
      LoadAccessoryDetailList();
    }
    #endregion

    #region Methods
    private void LoadCommonInfo()
    {
      int accessoryId;
      if (int.TryParse(hfAccessoryId.Value, out accessoryId))
      {
        #region Accessory
        AccessoryImport accessory = new AccessoryImportService().GetById(accessoryId);
        if (accessory != null)
        {
          txtRefNo.Text = accessory.RefNo;
          deImportDate.Date = accessory.ImportDate;
          txtTotalAmount.Value = accessory.TotalAmount;
          mmNote.Text = accessory.Notes;
        }
        #endregion
      }

      #region AccessoryDetail
      DataSet ds = new AccImportDetailService().GetByAccImportId(accessoryId).ToDataSet(true);
      if (ds != null && ds.Tables.Count > 0)
      {
        AccImportDetailTable = ds.Tables[0];
        AccImportDetailTable.PrimaryKey = new DataColumn[] { AccImportDetailTable.Columns["Id"] };
        AccImportDetailTable.Columns.Add("Deleted", typeof(bool));
      }
      #endregion
    }

    private void LoadAccessoryDetailList()
    {
      gvAccessoryDetail.DataSource = AccImportDetailTable;
      gvAccessoryDetail.FilterExpression = "Deleted <> true";
      gvAccessoryDetail.DataBind();
    }

    private string SaveAccessoryDetail()
    {
      try
      {
        int detailId;
        DataRow row = null;
        if (int.TryParse(hfDetailId.Value, out detailId))
        {
          row = AccImportDetailTable.Rows.Find(detailId);
        }

        if (row == null)
        {
          row = AccImportDetailTable.NewRow();
          row["Id"] = DetailId;
          DetailId--;
          AccImportDetailTable.Rows.Add(row);
        }

        row["Name"] = Utilities.SafeString(txtDetailName.Text);
        row["Quantity"] = Utilities.SafeString(txtDetailQuantity.Text);
        row["Amount"] = Convert.ToInt32(txtDetailAmount.Text);
        row["Deleted"] = false;

        return "SaveDetail";
      }
      catch (Exception ex)
      {
        WriteLog("AccessoryInfo::SaveAccessoryDetail", ex);
        return "Có lỗi trong quá trình lưu dữ liệu";
      }
    }

    private string DeleteAccessoryDetail(int id)
    {
      try
      {
        DataRow row = AccImportDetailTable.Rows.Find(id);
        if (row != null)
        {
          row["Deleted"] = true;
        }

        return "DeleteDetail";
      }
      catch (Exception ex)
      {
        WriteLog("AccessoryInfo::DeletePurchaseAccessoryDetail", ex);
        return "Có lỗi trong quá trình xóa dữ liệu";
      }
    }

    private string Save()
    {
      try
      {
        AccessoryImport accessory = null;
        AccessoryImportService accessoryService = new AccessoryImportService();
        using (TransactionScope scope = new TransactionScope())
        {
          int accessoryId;
          AccImportDetailService detailService = new AccImportDetailService();

          #region Accessory
          if (int.TryParse(hfAccessoryId.Value, out accessoryId))
          {
            accessory = accessoryService.GetById(accessoryId);
          }

          if (accessory == null)
          {
            accessory = new AccessoryImport();
          }

          accessory.ImportDate = deImportDate.Date;
          accessory.TotalAmount = Convert.ToInt32(txtTotalAmount.Text);
          accessory.UpdatedBy = CurrentUser.Username;
          accessory.UpdatedDate = DateTime.Now;
          accessory.Notes = mmNote.Text;

          accessoryService.Save(accessory);
          #endregion

          #region Detail
          foreach (DataRow row in AccImportDetailTable.Rows)
          {
            int detailId = Convert.ToInt32(row["Id"]);
            bool deleted = row["Deleted"] == DBNull.Value ? false : Convert.ToBoolean(row["Deleted"]);
            AccImportDetail detail = null;
            if (detailId > 0)
            {
              detail = detailService.GetById(detailId);
            }

            if (deleted)
            {
              #region Delete
              if (detail != null)
              {
                detailService.Delete(detail);
              }
              else
              {
                continue;
              }
              #endregion
            }
            else
            {
              #region Save
              if (detail == null)
              {
                detail = new AccImportDetail();
              }

              detail.AccImportId = accessory.Id;
              detail.Name = row["Name"].ToString();
              detail.Quantity = row["Quantity"].ToString();
              detail.Amount = Convert.ToInt32(row["Amount"]);

              detailService.Save(detail);
              row["Id"] = detail.Id;
              #endregion
            }
          }
          #endregion

          scope.Complete();
        }

        accessory = accessoryService.GetById(accessory.Id);
        return string.Format("Save|{0}|{1}", accessory.Id.ToString(), accessory.RefNo);
      }
      catch (Exception ex)
      {
        WriteLog("InportInfo::SaveAccessory", ex);
        return "Có lỗi trong quá trình lưu dữ liệu";
      }
    }
    #endregion
  }
}
